import time

import threading

import sqlite3

# 题目和答案

choice_questions = [

    {"question": "选择题1", "options": ["A", "B", "C", "D"], "answer": "A"},

    # ... 添加其他选择题

]

true_false_questions = [

    {"question": "判断1", "answer": "True"},

    # ... 添加其他判断题

]

short_answer_question = {"question": "问答题1", "answer": "标准答案"}

# 倒计时时间（秒）

countdown_time = 300  # 5分钟


# 答题函数

# 修改 answer_questions() 函数
def answer_questions(questions, question_type):
    print(f"开始回答{question_type}题")

    user_answers = []

    for idx, question in enumerate(questions, 1):
        print(f"\n问题{idx}: {question['question']}")

        if question_type == "选择题":
            options = question['options']
            answer = input(f"请选择答案（{', '.join(options)}）：")
        elif question_type == "判断题":
            answer = input("请判断正误（True/False）：")

        user_answers.append((question, answer))  # 存储题目字典及用户答案

    return user_answers

# 倒计时函数

class CountdownTimer(threading.Thread):
    def __init__(self, time_seconds, stop_event):
        super().__init__()
        self.time_seconds = time_seconds
        self.stop_event = stop_event
        self.show_timer = True  # 显示倒计时

    def run(self):
        for i in range(self.time_seconds, 0, -1):
            if self.stop_event.is_set():
                break

            if self.show_timer:
                mins, secs = divmod(i, 60)
                timer = '{:02d}:{:02d}'.format(mins, secs)
                print(f"剩余时间：{timer}")

            time.sleep(1)

        if not self.stop_event.is_set():
            print("\n时间到！自动交卷。")

    def show_countdown(self):
        self.show_timer = True
        # 主函数

def insert_quiz_results(participant_name, start_time, end_time, total_score, choice_score, true_false_score, short_answer_score):
    conn = sqlite3.connect('quiz_results.db')
    cursor = conn.cursor()

    cursor.execute('''
        CREATE TABLE IF NOT EXISTS quiz_results (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            participant_name TEXT,
            start_time TIMESTAMP,
            end_time TIMESTAMP,
            total_score INTEGER,
            choice_score INTEGER,
            true_false_score INTEGER,
            short_answer_score INTEGER
        )
    ''')

    cursor.execute('''
        INSERT INTO quiz_results (participant_name, start_time, end_time, total_score, choice_score, true_false_score, short_answer_score)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ''', (participant_name, start_time, end_time, total_score, choice_score, true_false_score, short_answer_score))

    conn.commit()
    conn.close()

    print("答题结果已成功存储到数据库。")
def main():
    stop_event = threading.Event()

    # 创建并启动倒计时线程
    timer_thread = CountdownTimer(countdown_time, stop_event)

    start_time = time.time()  # 记录答题开始时间

    timer_thread.start()

    # 用户答题
    choice_answers = answer_questions(choice_questions, "选择题")
    true_false_answers = answer_questions(true_false_questions, "判断题")

    short_answer = input(f"\n{short_answer_question['question']}\n请回答：")

    # 用户输入完毕后开始显示倒计时
    timer_thread.show_countdown()

    # 等待用户输入交卷指令
    print("\n如果您已完成所有题目，请输入'交卷'以结束答题。")

    while True:
        user_input = input()
        if user_input.lower() == '交卷':
            stop_event.set()  # 设置事件标志，停止倒计时
            break

    # 等待倒计时线程结束
    timer_thread.join()

    # 记录答题结束时间，并计算总答题时间
    end_time = time.time()
    total_time = end_time - start_time

    mins, secs = divmod(total_time, 60)

    print(f"\n答题总时间：{int(mins)}分钟{int(secs)}秒")

    # 计算选择题得分
    correct_choice_count = sum(answer == question['answer'] for question, answer in choice_answers)

    # 计算判断题得分
    correct_true_false_count = sum(answer == question['answer'] for question, answer in true_false_answers)

    # 计算问答题得分
    short_answer_correct = short_answer == short_answer_question['answer']
    if short_answer_correct:
        short_answer_score = 1
    else:
        short_answer_score = 0

    # 计算总分
    total_score = correct_choice_count + correct_true_false_count + short_answer_score

    # 输出结果
    print(f"答题结束。")
    print(
        f"\n选择题答对{correct_choice_count}道，判断题答对{correct_true_false_count}道，问答题{'正确' if short_answer_correct else '错误'}。")
    print(f"总得分：{total_score}分")


if __name__ == "__main__":
    main()


